// pages/recommendSong/recommendSong.js
import { REQUEST_RECOMMEND_SONGS } from "../../api/index.js";
import { getStorageSync, showToast, isEmptyObject } from "../../utils/util.js";
import pubsub from 'pubsub-js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    day: "", // 天
    month: "", // 月
    recommendList: [], // 推荐列表数据
    index: 0, // 点击音乐的下标
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const userInfo = getStorageSync("userInfo");
    if (isEmptyObject(userInfo)) {
      showToast({
        title: "请先登录",
        success: () => {
          wx.reLaunch({ url: "/pages/login/login" });
        },
      });
    }
    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1,
    });
    this.getRecommendList();
    pubsub.subscribe('switchType', (_, type) => {
      let { recommendList, index} = this.data;
      if (type === 'pre') {
        (index === 0) && (index = recommendList.length);
        index -= 1;
      } else {
        (index === recommendList.length -1) && (index = -1);
        index += 1;
      };
      this.setData({ index });
      const musicId = recommendList[index].id;
      pubsub.publish('musicId', musicId);
    });
  },
  async getRecommendList() {
    const cookies = getStorageSync("cookies");
    const MUSIC_U = cookies.length ? cookies.find((item) => item.includes("MUSIC_U")) : "";
    const { recommend, data } = await REQUEST_RECOMMEND_SONGS(
      {},
      { header: { cookie: MUSIC_U } }
    );
    this.setData({ recommendList: recommend });
  },
  toSongDetail(evt){
    const {song, index} = evt.currentTarget.dataset;
    this.setData({ index });
    wx.navigateTo({
      url: '/pages/songDetail/songDetail?musicId=' + song.id
    });
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
});
